package han.chensing.latos.maker.util;

import java.util.List;

import han.chensing.latos.common.level.content.objects.CommonNote;
import han.chensing.latos.maker.V;

public class TimeUtil {

    //FIXME Adapt to new bpm time line
    public static Float getNearestBeatTime(float absTime, List<Object[]> alignmentList){
        if (alignmentList==null|| alignmentList.isEmpty())
            return null;
        float bpm = V.project.getLatosMetaData().getDefaultBpm();
        float offset = V.project.getLatosMetaData().getOffset();
        float k = 60000f;
        float beat= bpm*(absTime+offset)/ k;
        float beatFloor= (float) Math.floor(beat);
        float leftBeat= (float) (beat-Math.floor(beat));
        int firstAlignmentM = (int) alignmentList.get(0)[0];
        float beatDis=leftBeat;
        for(int i=1;i<=firstAlignmentM+1;i++){
            float nowBeatDis=Math.abs(((float) i/firstAlignmentM)-leftBeat);
            if (nowBeatDis>=beatDis){
                float targetBeat = (float) (i-1) / firstAlignmentM + beatFloor;
                return targetBeat/bpm*k;
            }
            beatDis=nowBeatDis;
        }
        return null;
    }

    public static Float getNearestNoteTime(float absTime, List<CommonNote> commonNotes){
        if (commonNotes ==null)return null;
        if (commonNotes.isEmpty())return null;
        float firstTime = commonNotes.get(0).getStartTime();
        float lastDistance= Math.abs(firstTime -absTime);
        float outAbsTime=firstTime;
        for (CommonNote commonNote : commonNotes) {
            float noteTime = commonNote.getStartTime();
            float distance = Math.abs(noteTime-absTime);
            if (distance<=lastDistance){
                lastDistance=distance;
                outAbsTime=noteTime;
            }else {
                break;
            }
        }
        return outAbsTime;
    }
}
